<template>
  <el-row>
    <el-col :span="12">
      <el-tree
          ref="treeRef"
          :data="props.menuTreeData"
          show-checkbox
          :default-expand-all="true"
          node-key="id"
          highlight-current
          :props="defaultProps"
          @check-change="handleCheckChange"
      />
    </el-col>
    <el-col :span="12">
      <el-row :gutter="1">
        <el-col :span="12">
          <el-button class="button" type="primary" @click="editRoleMenus">保存</el-button>
        </el-col>
        <el-col :span="12">
          <el-button class="button">清除</el-button>
        </el-col>
      </el-row>
    </el-col>
  </el-row>
</template>

<script setup lang="ts">
import {reactive, toRefs, ref, watch, defineExpose} from 'vue'
import {allocMenuApi} from '../../../../request/api/role'
import { ElMessage } from 'element-plus'

const props = defineProps<{
  menuTreeData: MenuListItf[]
  roleMenus: RoleMenusItf
}>();

const state = reactive<{
  menuIds: Set<number>
  newRoleMenus: RoleMenusItf
}>({
  menuIds: new Set<number>(),
  newRoleMenus: {
    menuIds: []
  }
})

const {menuIds, newRoleMenus} = toRefs(state)

// 设置el-tree的配置
const defaultProps = {
  children: 'children',
  label: 'title',
}

const treeRef = ref()

// 吧角色值付给新的集合
watch(() => props.roleMenus, () => {
  // 调用el-tree的setCheckedKeys回显角色已经有的菜单 权限
  treeRef.value.setCheckedKeys(props.roleMenus.menuIds)
  // 先清空set里的所有值
  menuIds.value = new Set<number>()
  for (const key in props.roleMenus.menuIds) {
    menuIds.value.add(props.roleMenus.menuIds[key])
  }
})

// checkbox点击事件
const handleCheckChange = (targetObj: MenuListItf, checkTarget: boolean) => {
  if (checkTarget) {
    menuIds.value.add(targetObj.id as number)
  } else {
    menuIds.value.delete(targetObj.id as number)
  }
}

// 点击保存按钮
const editRoleMenus = () => {
  if (!props.roleMenus.roleId) {
    ElMessage({
      message: '请先右侧选择一个角色！',
      type: 'warning',
    })
    return
  }
  // 把set里的值转成新对象
  newRoleMenus.value = {
    roleId: props.roleMenus.roleId,
    menuIds: [...menuIds.value]
  }

  allocMenuApi(newRoleMenus.value).then(res => {
    if (res.code === 200) {
      console.log(res)
    }
  })
}

</script>
<style lang="less" scoped>
</style>
